using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using E4RPDevExpress10;
using TakeAway.DataSet;

namespace TakeAway.Controls
{
    public partial class AssignedXtraUserControl : XtraUserControl, IGridView,  IAssignEmployee
    {
        private Controller _controller;
        private PedidoDataSet _dataSet;
        
        public Controller Controller
        {
            set
            {
                _controller = value;
                SetDataSource();
                _controller.RequestSaved += delegate { SetDataSource(); };
                _controller.RequestsRefreshed += delegate { SetDataSource(); };
                SetupLocalTypeData();
            }
        }

        public AssignedXtraUserControl()
        {
            InitializeComponent();
            GotFocus += AssignedXtraUserControlGotFocus;
            gridView.DoubleClick+= GridViewDoubleClick;
            closeRepositoryItemButtonEdit.ButtonClick += CloseRepositoryItemButtonEditButtonClick;
            gridView.CustomUnboundColumnData += GridViewCustomUnboundColumnData;
        }

        private void SetDataSource()
        {
            gridView.BeginUpdate();
            _dataSet = _controller.GetBilledRequests();
            gridControl.DataSource = _dataSet;
            gridControl.DataMember = _dataSet.Pedido.TableName;            
            gridView.EndUpdate();
        }
        
        private string GetShop()
        {
            if (gridView.SelectedRowsCount == 0)
                return "";
            string shop = "";
            foreach (int rowHandle in gridView.GetSelectedRows())
            {
                var request = (PedidoDataSet.PedidoRow) gridView.GetDataRow(rowHandle);
                if (shop != "" && request.Loja != shop)
                    return "";
                shop = request.Loja;
            }
            return shop;
        }

        private void SetupLocalTypeData()
        {
            var dataSet = new TipoLocalDataSet();
            dataSet.Merge(_controller.GetLocalType());
            localTypeRepositoryItemLookUpEdit.DataSource = dataSet.TipoLocal;
            localTypeRepositoryItemLookUpEdit.DisplayMember = dataSet.TipoLocal.NomeColumn.ToString();
            localTypeRepositoryItemLookUpEdit.ValueMember = dataSet.TipoLocal.IdColumn.ToString();
            localTypeRepositoryItemLookUpEdit.Columns.Clear();
            localTypeRepositoryItemLookUpEdit.Columns.AddRange(new[]
                                                                   {
                                                                       new LookUpColumnInfo("Id", "Id", 70, FormatType.None, "", false, HorzAlignment.Near),
                                                                       new LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)
                                                                   });
        }


        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "TakeAway.Controls.AssignedXtraUserControl"; }
        }

        public void Assign()
        {
            string shop = GetShop();
            if (shop == "")
                return;
            var employee = new AssignEmployeeXtraForm {Controller = _controller, Shop = shop};
            var result = employee.ShowDialog();
            if (result != DialogResult.OK)
                return;
            var requestIds = new List<PedidoDataSet.PedidoRow>();
            foreach (int rowHandle in gridView.GetSelectedRows())
                requestIds.Add((PedidoDataSet.PedidoRow)gridView.GetDataRow(rowHandle));
            foreach (PedidoDataSet.PedidoRow request in requestIds)
            {
                DateTime? dateTime = null;
                if(!string.IsNullOrEmpty(employee.EmployeeName)) dateTime = DateTime.Now;
                _controller.AssignEmployee(request.Id, employee.EmployeeName, dateTime, request.IsExternoIdNull() ? "" : request.ExternoId);
            }
        }

        public PedidoDataSet.PedidoRow GetSelectedRequest()
        {
            if(gridView.SelectedRowsCount == 0)
                return null;
            return (PedidoDataSet.PedidoRow)gridView.GetDataRow(gridView.GetSelectedRows()[0]);
        }


        private void GridViewDoubleClick(object sender, EventArgs e)
        {
            if (!_controller.ExistsOpenedRequest(this, "Deseja mesmo efectuar abrir pedido?"))
                return;
            var request = (PedidoDataSet.PedidoRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (request == null)
                return;            
            _controller.ShowRequest(request.Id);
        }

        private void CloseRepositoryItemButtonEditButtonClick(object sender, ButtonPressedEventArgs e)
        {
            var request = (PedidoDataSet.PedidoRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (request == null || request.IsExternoIdNull())
                return;
            var result = MessageBox.Show(this, "Deseja mesmo fechar o pedido?", "Pedido", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.No)
                return;
            _controller.CloseRequest(request);
        }

        void AssignedXtraUserControlGotFocus(object sender, EventArgs e)
        {
            gridView.FocusedColumn = colEmissao;
            gridView.FocusedColumn = colAtribuido;
        }

        void GridViewCustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column == colEmitidoA)
            {
                var request = (PedidoDataSet.PedidoRow) gridView.GetDataRow(e.RowHandle);
                if (request == null)
                    return;
                TimeSpan time = DateTime.Now - request.Emissao;
                e.Value = time.Hours.ToString().PadLeft(2, '0') + ":" + time.Minutes.ToString().PadLeft(2, '0');
                return;
            }
            if (e.Column == colAtribuidoA)
            {
                var request = (PedidoDataSet.PedidoRow)gridView.GetDataRow(e.RowHandle);
                if (request == null || request.IsAtribuidoNull())
                    return;
                TimeSpan time = DateTime.Now - request.Atribuido;
                e.Value = time.Hours.ToString().PadLeft(2, '0') + ":" + time.Minutes.ToString().PadLeft(2, '0');
                return;
            }
        }
        
    }
}
